package cs294s.liveradar.service;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.database.DataSetObserver;
import android.os.Handler;
import android.util.Log;

public class Observed {


	/**
	 * True if we are in the process of loading
	 */
	protected boolean mLoading;
	
	/**
	 * Observers interested in changes to the current list of feeds
	 */
	private ArrayList<WeakReference<DataSetObserver>> mObservers = 
		new ArrayList<WeakReference<DataSetObserver>>();


	/**
	 * Adds an observer to be notified when the set of items held by this BlipManager changes.
	 */
	public synchronized void addObserver(DataSetObserver observer) {
		Log.d("RADAR", "ADD OBSERVER");
		WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer);
		mObservers.add(obs);
	}

	public synchronized void removeObserver(DataSetObserver observer) {
		final ArrayList<WeakReference<DataSetObserver>> observers = mObservers;
		final int count = observers.size();
		for (int i = count - 1; i >= 0; i--) {
			WeakReference<DataSetObserver> weak = observers.get(i);
			DataSetObserver obs = weak.get();
			if(obs == observer)
				observers.remove(i);
		}
	}
	

	/**
	 * Called when something changes in our data set. Cleans up any weak references that
	 * are no longer valid along the way.
	 */
	protected synchronized void notifyObservers() {

		Log.d("RADAR", "NOTIFYING OBSERVERS");
		final ArrayList<WeakReference<DataSetObserver>> observers = mObservers;
		final int count = observers.size();
		for (int i = count - 1; i >= 0; i--) {
			WeakReference<DataSetObserver> weak = observers.get(i);
			DataSetObserver obs = weak.get();
			if (obs != null) {
				obs.onChanged();
			} else {
				observers.remove(i);
			}
		}

	}
	

	/**
	 * @return True if we are still loading content
	 */
	public boolean isLoading() {
		return mLoading;
	}
}
